using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Net;
using System.Web;
using System.IO;

namespace GameHacker.Login
{
    public partial class LoginForm : DevExpress.XtraEditors.XtraForm
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUsername.Text))
            {
                MessageBox.Show("plz input username.");
                txtUsername.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                MessageBox.Show("plz input password.");
                txtPassword.Focus();
                return;
            }

            if (CheckPassword(txtUsername.Text, txtPassword.Text))
            {
                HttpWebRequest request = D2xstudio.Net.Utilty.CreateHttpWebRequest("http://pass.tom.com/dologin.php", D2xstudio.Net.WebRequestMethod.POST);
                string postData = string.Format("tomid={0}&tompwd={1}&issave=on&svcid=21&backurl=http%3A%2F%2Fgame.tom.com%2Findex.php",
                HttpUtility.UrlEncode(txtUsername.Text),
                HttpUtility.UrlEncode(txtPassword.Text));
                byte[] postByteData = Encoding.ASCII.GetBytes(postData);
                request.ContentLength = postByteData.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postByteData, 0, postByteData.Length);
                request.AllowAutoRedirect = false;

                try
                {
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    string setCookie = response.Headers[HttpResponseHeader.SetCookie];
                    if (!string.IsNullOrEmpty(setCookie))
                    {
                        int index = setCookie.IndexOf(';');
                        string sessionCookie = setCookie.Substring(0, index);

                        LoadGame(setCookie, sessionCookie);

                        this.Hide();
                        MainForm mainForm = new MainForm(sessionCookie);
                        mainForm.Show();
                    }
                    else
                    {
                        MessageBox.Show("login failed, plz contact tom.");
                    }
                }
                catch
                {
                    MessageBox.Show("login failed. try again.");
                    return;
                }
                
                
            }
            else
            {
                MessageBox.Show("plz check passowrd and login agin.");
            }

            
        }

        private bool CheckPassword(string username, string password)
        {
            HttpWebRequest request = D2xstudio.Net.Utilty.CreateHttpWebRequest("http://game.tom.com/service/register_service.php", D2xstudio.Net.WebRequestMethod.POST);
            request.ProtocolVersion = HttpVersion.Version10;
            string postData = string.Format(
                    "operation=authuser&username={0}&password={1}",
                    HttpUtility.UrlEncode(txtUsername.Text),
                    HttpUtility.UrlEncode(txtPassword.Text));
            byte[] postByteData = Encoding.ASCII.GetBytes(postData);
            request.ContentLength = postByteData.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postByteData, 0, postByteData.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            List<byte> result = new List<byte>();
            byte[] buffer = new byte[256];
            int readedCount = 0;
            do
            {
                readedCount = responseStream.Read(buffer, 0, buffer.Length);
                byte[] temp = new byte[readedCount];
                Array.Copy(buffer, temp, readedCount);
                result.AddRange(temp);                
            } while (readedCount > 0);

            string responseContent = D2xstudio.Net.Zip.DeCompress(result.ToArray());


            if (responseContent == "1")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void LoadGame(string allCookie, string sessionCookie)
        {
            StringBuilder loginCookie = new StringBuilder();
            int indexName = allCookie.IndexOf("TOM_USERNAME");
            int indexValue = allCookie.Substring(indexName).IndexOf(';');
            loginCookie.AppendFormat("TOM_USERNAME={0};", allCookie.Substring(indexName + 13, indexValue - 13));

            indexName = allCookie.IndexOf("TOM_NEW_PASS");
            indexValue = allCookie.Substring(indexName).IndexOf(';');
            loginCookie.AppendFormat("TOM_NEW_PASS={0};", allCookie.Substring(indexName + 13, indexValue - 13));

            HttpWebRequest request = D2xstudio.Net.Utilty.CreateHttpWebRequest("http://game.tom.com/service/transfer_service.php?gameid=44&servernumber=12");
            request.AllowAutoRedirect = false;
            request.Headers[HttpRequestHeader.Cookie] = loginCookie.ToString();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string address = response.Headers[HttpResponseHeader.Location];

            request = D2xstudio.Net.Utilty.CreateHttpWebRequest(address);
            request.AllowAutoRedirect = false;
            request.Headers[HttpRequestHeader.Cookie] = sessionCookie;
            response = (HttpWebResponse)request.GetResponse();
        }
    }
}